/** To import SVGs:
 * 1. In Figma, select one of the icons inside the Icons container and select them with CTRL+A (or ⌘+A on Mac). Export them with the SVG type.
 * 2. Unzip the downloaded file, and copy the SVGs into the \`src/icons\` directory.
 * 3. Run this script
 **/

import fs from "fs/promises";
import path from "path";

const filesToIgnore = ["AllIcons.tsx"];
/** Use this to map an invalid name temporarily (until it is fixed in the Figma)  */
const iconNameMapping = {};

function getIconName(svg) {
  const result = svg.replace(".svg", "");
  return iconNameMapping[result] ?? result;
}

async function processSvgsInFolder(folder) {
  // Start by renaming the files to remove the "Type=" or "Property 1=" prefix
  await Promise.all(
    (await fs.readdir(folder, { recursive: true })).map(async (name) => {
      if (name.includes("=")) {
        const currentPath = name.split("/").slice(0, -1).join("/");
        const newName = path.join(
          folder,
          currentPath + "/" + name.split("=")[1]
        );
        if (await fs.access(newName).catch(() => false)) {
          await fs.unlink(newName);
        }
        await fs.rename(path.join(folder, name), newName);
      }
    })
  );

  const svgs = await fs.readdir(folder, { recursive: true });
  await Promise.all(
    svgs
      .filter((svg) => svg.endsWith(".svg"))
      .map(async (svg) => {
        console.log(path.join(folder, svg));
        const svgContent = await fs.readFile(path.join(folder, svg), "utf8");
        const result = svgContent
          .replace(/stroke="#160F1F"/g, 'stroke="currentColor"')
          .replace(/fill="#160F1F"/g, 'fill="currentColor"')
          .replace(/width="24"/g, 'width="100%"')
          .replace(/height="24"/g, 'height="100%"');
        await fs.writeFile(path.join(folder, svg), result, "utf8");
      })
  );
}

async function createIndexFile(folder) {
  const header = `/**\n * This file is auto-generated by the \`import-svgs.mjs\` script.\n */`;
  const stuffInDir = await fs.readdir(folder);
  const foundSvgs = [];
  const foundTsx = [];
  const foundFolders = [];
  await Promise.all(
    stuffInDir.map(async (stuff) => {
      if (filesToIgnore.includes(stuff)) {
        return;
      }

      if (stuff.endsWith(".svg")) {
        foundSvgs.push(stuff);
      } else if (stuff.endsWith(".tsx")) {
        foundTsx.push(stuff);
      } else if ((await fs.stat(path.join(folder, stuff))).isDirectory()) {
        foundFolders.push(stuff);
      }
    })
  );
  await Promise.all(
    foundFolders.map(async (f) => {
      await createIndexFile(path.join(folder, f));
    })
  );
  const content = foundSvgs
    .map(
      (svg) =>
        `export { default as ${getIconName(svg)} } from "./${svg}?react";`
    )
    .concat(foundTsx.map((tsx) => `export * from "./${tsx}";`))
    .concat(
      foundFolders.map(
        (folder) => `export * as ${folder} from "./${folder}/index.ts";`
      )
    )
    .join("\n");

  await fs.writeFile(
    path.join(folder, "index.ts"),
    `${header}\n\n${content}\n`,
    "utf8"
  );
}

const currentDir = import.meta.dirname;
const dirToProcess = path.join(currentDir, "../src/icons");
await processSvgsInFolder(dirToProcess);
await createIndexFile(dirToProcess);
